package com.lzx.applib.gson;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Lzx on 16/11/23 0023.
 */
public class ListTypeAdapter implements JsonDeserializer<List<?>> {
    public static final String TAG = "ListTypeAdapter";

    @Override
    public List<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonArray()) {
            JsonArray jsonArray = (JsonArray) json;
            List list = new ArrayList();
            Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
            for (int i = 0; i < jsonArray.size(); i++) {
                JsonElement element = jsonArray.get(i);
                Object item = context.deserialize(element, itemType);
                list.add(item);
            }
            return list;
        }
        return Collections.EMPTY_LIST;
    }
}
